﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UI.ParentForm;
using UI.Lib.Factory;
using UI.Lib;
using Components;
using System.Collections;
using Model;

namespace UI.ProductManagement
{
    public partial class FrmPot4a00NMedit : BaseTMedit
    {
        private string[] keys = null;

        bool _isDeferLoad = false; //是否延迟做查询

        public FrmPot4a00NMedit(string modulecode, string action, string text, string[] key)
            : base(modulecode, action)
        {
            InitializeComponent();

            this.Text = text;
            keys = key;

            //回写的方法
            this.SaveCallFuntion = "Pot4a00Manager$SaveData"; //保存的方法
            IsAfterSaveCloseWin = false;
            this.allowDtlEmpty = false; //可能用户一次想把全部的记录删除
            if (null != keys)
            {
                IsAfterSaveCloseWin = true;
                LoadData();
            }

            if ("X" == this.Action)
            {
                this.tspBtnAdd.Visible = false;
                this.tspBtnDel.Visible = false;
                this.panOp.Enabled = false;
            }

            LoadUserControlData();
        }

        protected void LoadUserControlData()
        {
            //加载所有销售商, 条件为公司 + 状态
            DataTable dtSellers = CommonHelper.Entity.ExecFun("getsellers",
                new KeyValuePair<string, object>("muser", Context.Comocde),
                 new KeyValuePair<string, object>("word", txtQuerySeller.Text));
            if (dtSellers == null || dtSellers.Rows.Count == 0) return;

            BindListBox(dtSellers, lstSeller, true);
        }

        private void panDtl_LocationChanged(object sender, EventArgs e)
        {
            this.panOp.Location = new Point(this.panDtl.Width + this.panDtl.Location.X + 10,
                this.panDtl.Location.Y);

            this.panOp.Height = this.panDtl.Height;
        }

        private void lstSeller_SelectedValueChanged(object sender, EventArgs e)
        {
            if (_isDeferLoad) return; //只用用于全选时提高速度

            //清空列表
            this.lstShop.Items.Clear();

            string sid = GetListBoxSelectedValues(lstSeller); //得到销售商被选项集合
            string alreayid = GetListBoxValues(lstHave, true); //得到已经选择的门店编码，方便做过滤
            if (string.IsNullOrEmpty(sid)) return;

            //加载门店, 条件为销售商 + 状态 + 已经选择的门店
            DataTable dtShops = CommonHelper.Entity.ExecFun("getshoplistbysellerid", new KeyValuePair<string, object>("I%sid", sid),
                 new KeyValuePair<string, object>("I%notid", alreayid),
                 new KeyValuePair<string, object>("word", txtQueryShop.Text));

            BindListBox(dtShops, lstShop, true);

            _isDeferLoad = false;
        }


        /// <summary>
        /// 将目标下拉框多选的值以字符串的形式返回
        /// </summary>
        /// <param name="box"></param>
        /// <returns></returns>
        string GetListBoxSelectedValues(ListBox box)
        {
            System.Windows.Forms.ListBox.SelectedObjectCollection items = box.SelectedItems;
            if (items.Count == 0) return "";

            StringBuilder sb = new StringBuilder();
            TextValuePair tv;
            foreach (object o in items)
            {
                tv = o as TextValuePair;

                if (null == tv) continue;

                if (sb.Length > 0) sb.Append(",");
                sb.Append(tv.Value); //得到主键
            }

            return sb.ToString();
        }

        /// <summary>
        /// 得到值集合
        /// </summary>
        /// <param name="box"></param>
        /// <param name="isFindChildId">是否找到真正的ID</param>
        /// <returns></returns>
        string GetListBoxValues(ListBox box, bool isFindChildId)
        {
            var items = box.Items;
            if (items.Count == 0) return "";

            StringBuilder sb = new StringBuilder();
            TextValuePair tv;
            string val;
            foreach (object o in items)
            {
                tv = o as TextValuePair;

                if (null == tv) continue;
                val = Validation.ToString(tv.Value);
                if (isFindChildId && val.IndexOf(';') > -1) //Listbox中门店的标识是用销售商;门店编码标识的
                {
                    val = val.Substring(val.IndexOf(';') + 1);
                }

                if (sb.Length > 0) sb.Append(",");
                sb.Append(val); //得到主键
            }

            return sb.ToString();
        }

        private void lnkJoin_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Windows.Forms.ListBox.SelectedObjectCollection items = lstShop.SelectedItems;
            List<object> os = new List<object>();

            foreach (object objItem in items)
            {
                this.lstHave.Items.Add(objItem);

                os.Add(objItem); //需要移除的列表
            }

            foreach (object o in os)
            {
                lstShop.Items.Remove(o);
            }
        }

        /// <summary>
        /// 由于直接绑定DataTable在Box上的话，会导致对项操作不太方便的情况，所以只能一项一项的绑定了
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="box"></param>
        void BindListBox(DataTable dt, ListBox box, bool isClearAllFirst)
        {
            if (isClearAllFirst) box.Items.Clear();
            if (dt == null || dt.Rows.Count == 0) return;

            foreach (DataRow dr in dt.Rows)
            {
                box.Items.Add(new TextValuePair(Validation.ToString(dr["text"]),
                    Validation.ToString(dr["value"])));
            }
        }

        private void lstHave_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            int i = this.lstHave.SelectedIndex;
            if (i < 0) return;
            //做移除操作
            this.lstHave.Items.RemoveAt(i);
        }

        private void lstShop_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            lnkJoin_LinkClicked(null, null);
        }

        /// <summary>
        /// 复选框的全选和全部取消
        /// </summary>
        /// <param name="ListBox"></param>
        /// <param name="b"></param>
        private static void SelectAll(ListBox ListBox, bool b)
        {
            for (int i = 0; i < ListBox.Items.Count; i++)
            {
                ListBox.SetSelected(i, b);
            }
        }

        private void lnksellerALl_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            _isDeferLoad = true; //延迟触发查询方法

            SelectAll(lstSeller, true);

            _isDeferLoad = false;

            lstSeller_SelectedValueChanged(null, null);
        }

        private void lnksellunAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            _isDeferLoad = true;
            SelectAll(lstSeller, false);

            this.lstShop.Items.Clear();
            _isDeferLoad = false;
        }

        private void lnkshopAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SelectAll(lstShop, true);
        }

        private void lnkshopunAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            SelectAll(lstShop, false);
        }

        protected override bool Check()
        {
            //验证开始时间必须要小于结束时间
            DateTime startdate = Convert.ToDateTime(this.tbSummary.GetValue("startdate"));
            DateTime endate = Convert.ToDateTime(this.tbSummary.GetValue("endate"));
            if ("A" == this.Action)
            {
                System.Collections.Hashtable hs = new System.Collections.Hashtable();
                hs["promocode"] = this.tbSummary.GetValue("promocode");
                hs["%muser"] = UI.Lib.Context.GetAppKeyWhere();
                bool reflt = UI.Lib.Factory.CommonHelper.Entity.DataInData("Pot4a00", hs);
                hs = null;
                if (reflt)
                {
                    MessageBox.Show("当前促销代码已经存在！", "提示");
                    this.tbSummary.Focus("promocode");
                    return false;
                }
            }

            if ("X" == this.Action || "A" == this.Action)
            {
                if (startdate.Subtract(endate).Days > 0)
                {
                    MessageBox.Show("【促销截止日】不能小于【促销开始日】！", "提示");
                    this.tbSummary.Focus("endate");
                    return false;
                }
            }

            if (this.lstHave.Items.Count == 0)
            {
                MessageBox.Show("本次促销的目标门店必须选择，不能保存！", "提示");
                return false;
            }

            //检查同一时期的其他促销信息
            if ("A" == Action || "M" == Action)
            {
                Hashtable where = new Hashtable();
                where["sta"] = startdate;
                where["end"] = endate;
                where["code"] = Validation.ToString(this.tbSummary.GetValue("promocode"));
                DataTable info = CommonHelper.Entity.ExecFun("checkprom", where);

                string msg = UIHelper.TranslateInfo(info, string.Format("{0}到{1}其他的促销信息如下:",
                    startdate.ToShortDateString(), endate.ToShortDateString()), 30);
                if (!string.IsNullOrEmpty(msg))
                {
                    MessageBox.Show(msg, "提示");
                }
            }

            return true;
        }

        protected override bool BeforeDtlPopUp(string name, ref string where, ref string[] others)
        {
            if ("productcode" == name)
            {
                where = string.Format(" status = '1' {0}", Context.GetAppKeyWhere("muser", true));
            }

            return true;
        }

        //加载修改数据
        private void LoadData()
        {
            base.LoadEditData(null, string.Format(" a.promocode ='{0}'  "
             , this.keys[0]));
            base.LoadDtlData(null, string.Format(" a.promocode ='{0}'  "
                , this.keys[0]));

            //绑定门店
            DataTable dtShops = CommonHelper.Entity.ExecFun("getpot4a01list",
                    new KeyValuePair<string, object>("code", this.keys[0]));
            if (dtShops == null || dtShops.Rows.Count == 0) return;

            BindListBox(dtShops, lstHave, false);
        }

        public override void AfterDtlPopWin(string name, Hashtable data, bool ischange)
        {
            if ("productcode" == name)
            {
                this.dgvDtl.Focus("nprice"); //选择完货号后焦点自动带入促销价格栏目
            }
        }

        /// <summary>
        /// 将选定的门店列表返回到服务器
        /// </summary>
        /// <returns></returns>
        protected override Hashtable SaveOtherData()
        {
            Hashtable tb = new Hashtable();
            tb["shoplist"] = GetListBoxValues(lstHave, false);
            return tb;
        }

        protected override void AfterSaveData(bool isSuccess)
        {
            if (isSuccess)
            {
                this.lstHave.Items.Clear();
                this.lstSeller.Items.Clear();
                this.lstShop.Items.Clear();
            }
        }

        protected override void AfterDtlValueChanged(string name, object value)
        {
            if ("nprice" == name) //促销价如果
            {
                //原价
                double oprice = Validation.ToDouble(this.dgvDtl.GetValue("oprice"));
                double nowPrice = Validation.ToDouble(value);

                if (oprice < nowPrice)
                {
                    if (MessageBox.Show("当前商品的促销价大于了原价格, 是否继续？", "提示", MessageBoxButtons.YesNo)
                        == DialogResult.No)
                    {
                        this.dgvDtl.SetValue(name, "0");
                        this.dgvDtl.Focus(name);
                    }
                }

                //成本
                double pamt = Validation.ToDouble(this.dgvDtl.GetValue("pamt"));
                //计算毛利率
                double pct = Validation.ToDouble(((nowPrice - pamt) / nowPrice), 3);
                this.dgvDtl.SetValue("pct", pct);
            }
        }

        private void txtQuerySeller_TextChanged(object sender, EventArgs e)
        {
            LoadUserControlData();
        }

        private void txtQueryShop_TextChanged(object sender, EventArgs e)
        {
            lstSeller_SelectedValueChanged(null, null);
        }

        protected override void ResetSize()
        {
            base.ResetSize();

            this.panOp.Location = this.panOp.Location;
            this.panOp.Size = new Size(this.panOp.Width, this.panDtl.Height);
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            int i = this.lstHave.SelectedIndex;
            if (i < 0) return;
            //做移除操作
            this.lstHave.Items.RemoveAt(i);
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            lstHave.Items.Clear();
        }
    }
}

